<template>
  <div>
    <el-badge :value="validMentionLen" class="item">
      <el-button type="primary" @click="dialogTableVisible = true">提醒</el-button>
    </el-badge>
    <el-dialog v-model="dialogTableVisible" title="提醒信息" width="900" max-height="400">
      <Filter
        :isCreate="true"
        :items="['onLineState', 'source', 'lessPrice', 'overNum', 'subType']"
        @search="addMention"
      />
      <el-table :data="mentionArrResult">
        <el-table-column property="onLineState" label="在线状态" />
        <el-table-column property="source" label="物品" />
        <el-table-column property="lessPrice" label="小于n白鸡" />
        <el-table-column property="overNum" label="超过n个" />
        <el-table-column property="subType" label="已/未揭示" />
        <el-table-column property="isOn" label="是否开启" width="200px">
          <template #default="scope">
            <el-switch
              :model-value="scope.row.isOn"
              @change="editMention(scope.row.id)"
              style="margin-right: 14px"
            />
            <el-button size="small" type="danger" @click="deleteMention(scope.row.id)">
              删除
            </el-button>
            <el-button size="small" type="primary" @click="view(scope.row.id)"> 查看 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog v-model="infoDialogVisible" title="监控结果" width="1400" max-height="400">
      <div style="width: 100%; height: 400px">
        <el-auto-resizer>
          <template #default="{ height, width }">
            <el-table-v2 :columns="columns" :data="data" :width="width" :height="height" fixed />
          </template>
        </el-auto-resizer>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import { get, set } from '@/storage/index';
import Filter from '@/component/Filter.vue';
import { computed, ref } from 'vue';
import { MentionResult, NoMention, OperateType, type TypeMention } from '@/types/mention';
import { Form } from '@/types/filter';
import config from '@/config';
import { type ColumnItem } from '@/types/table';
import { ElButton } from 'element-plus';
const { statusOptions, subtypeOptions, soruceOptions } = config;
import { copyToClipboard } from '@/utils/tools';
interface Props {
  mentionResultArr: MentionResult[];
}
const props = withDefaults(defineProps<Props>(), {
  mentionResultArr: () => []
});

interface Emits {
  (e: 'setMention', value: TypeMention[]): void;
  (e: 'setNoMention', noMention: NoMention, type: OperateType): void;
}
const emits = defineEmits<Emits>();

const message = (str: string, data: NoMention) => {
  copyToClipboard(str);
  emits('setNoMention', data, OperateType.add);
  ElMessage.success('已复制到剪贴板');
};

const columns: ColumnItem[] = [
  {
    key: 'ingameName',
    dataKey: 'ingameName',
    title: '用户',
    width: 150
  },
  {
    key: 'reputation',
    dataKey: 'reputation',
    title: '声誉',
    width: 150
  },
  {
    key: 'source',
    dataKey: 'source',
    title: '物品',
    width: 150
  },
  {
    key: 'status',
    dataKey: 'status',
    title: '在线状态',
    width: 150
  },
  {
    key: 'platinum',
    dataKey: 'platinum',
    title: '价格',
    width: 150
  },
  {
    key: 'quantity',
    dataKey: 'quantity',
    title: '个数',
    width: 150
  },
  {
    key: 'subtype',
    dataKey: 'subtype',
    title: '是否揭示',
    width: 150
  },
  {
    key: 'chat',
    dataKey: 'chat',
    width: 150,
    title: '联系',
    // @ts-ignore
    cellRenderer: ({ cellData: chat }) => (
      <>
        <ElButton size="small" type="primary" onClick={message.bind(this, chat.chatMsg, chat.data)}>
          联系他
        </ElButton>
      </>
    )
  }
];

// 弹框是否开启
const dialogTableVisible = ref<boolean>(false);
// 查看弹框
const infoDialogVisible = ref<boolean>(false);
const visibleId = ref<number>(1);
const data = computed(
  () => props.mentionResultArr.find(item => item?.id === visibleId.value)?.result
);

const view = (id: number) => {
  visibleId.value = id;
  if (!data.value) {
    ElMessage.error('暂时没有提醒数据！');
    return;
  }
  infoDialogVisible.value = true;
};
const mentionArr = ref<TypeMention[]>([]);

const validMentionLen = computed(
  () => mentionArr.value.filter(item => item.isOn && item.valid).length
);
const getStorage = () => {
  get('mention')
    .then(res => {
      if (res) {
        mentionArr.value = res as TypeMention[];
      }
    })
    .finally(() => {
      emits('setMention', mentionArr.value);
    });
};
getStorage();

const chinesize = (data: TypeMention) => {
  data.onLineState = data.onLineState.map(item => statusOptions[item]);
  data.source = data.source.map(item => soruceOptions[item]);
  data.subType = data.subType.map(item => subtypeOptions[item]);
  return data;
};
const mentionArrResult = computed(() => {
  const tempArr = JSON.parse(JSON.stringify(mentionArr.value));
  // @ts-ignore
  return tempArr.filter(item => item.valid).map(item => chinesize(item));
});

const addMention = (data: Form) => {
  // 类型谓词
  const isMention = (formData: Form | TypeMention): formData is TypeMention => {
    return !(formData as Form).time;
  };
  if (isMention(data)) {
    const maxId = Math.max(...mentionArr.value.map(item => item.id));
    mentionArr.value.push({
      ...data,
      isOn: true,
      valid: true,
      id: maxId === -Infinity ? 1 : maxId + 1
    });
    set('mention', mentionArr.value);
    emits('setMention', mentionArr.value);
  }
};

const deleteMention = (id: number) => {
  mentionArr.value.find(item => {
    if (item.id === id) {
      item.valid = false;
      return;
    }
  });
  set('mention', mentionArr.value);
  emits('setMention', mentionArr.value);
};

const editMention = (id: number) => {
  mentionArr.value.find(item => {
    if (item.id === id) {
      item.isOn = !item.isOn;
    }
  });
  set('mention', mentionArr.value);
  emits('setMention', mentionArr.value);
};
</script>

<style scoped lang="less"></style>
